/*************************************************************************
	> File Name: mysql_api.c
	> Author: 
	> Mail: 
	> Created Time: Tue 30 Mar 2021 05:36:03 PM CST
 ************************************************************************/

#include "head.h"

extern MYSQL *conn_ptr;

void getNowTime(char *time_str, int size) {
	time_t now = time(NULL);
	strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));
}

MYSQL *connectDB(char *ipAddr, char *user, char * passwd, char *db, unsigned int port) {
	MYSQL *conn_ptr;
	conn_ptr = mysql_init(NULL);
	if (!conn_ptr) {
		return NULL;
	}
	conn_ptr = mysql_real_connect(conn_ptr, ipAddr, user, passwd, db, port, NULL, 0);
	if (!conn_ptr) {
		return NULL;
	}
	return conn_ptr;
}

int insert_slaveInfo(struct slaveInfo si) {
	if (si.name == NULL || si.ip == NULL) {
		return -1;
	}
	char sql[1024] = {0};
	if (si.id == 0 && si.updateTime != NULL) {
		sprintf(sql, "INSERT INTO slaveInfo (si.name, ip, updateTime) VALUES ('%s', '%s', '%s')", si.name, si.ip, si.updateTime);
	} else if (si.id != 0 && si.updateTime == NULL) {
		sprintf(sql, "INSERT INTO slaveInfo (id, name, ip) VALUES ('%d', '%s', '%s')", si.id, si.name, si.ip);
	} else if (si.id == 0 && si.updateTime == NULL) {
		sprintf(sql, "INSERT INTO slaveInfo (name, ip) VALUES ('%s', '%s')", si.name, si.ip);
	} else {
		sprintf(sql, "INSERT INTO slaveInfo (id, name, ip, updateTime) VALUES ('%d', '%s', '%s', '%s')", si.id, si.name, si.ip, si.updateTime);
	}
	int res;
    if (res = (mysql_query(conn_ptr, sql))) {
        // fprintf(stderr, "SELECT error: %s\n", mysql_error(conn_ptr));
		return res;
    }
	return res;
}

int update_slaveInfo(struct slaveInfo si, struct slaveInfo_select sis) {
	int res;
	if (sis.id == 0 && sis.ip == 0 && sis.name == 0 && sis.updateTime == 0) {
		res = mysql_query(conn_ptr, "SELECT * FROM slaveInfo");
		return res;
	}
	
}